#coding=utf-8
from uliweb import expose, decorators
from uliweb.orm import get_model

perm = 'SelfDevPollAdmin'

@expose('/poll/selfdev')
class SelfDevPollView(object):
    def __init__(self):
        self.model = get_model('selfdevpoll_modules')
        self.Poll = get_model('poll')
        self.Result = get_model('selfdevpoll_user')
        self.Selection = get_model('selfdev_selection')
        Kfzx = get_model('kfzx')
        self.depart_condition = (Kfzx.c.type.in_(['1', '2'])) | (Kfzx.c.id.in_([10]))
        
    @expose('')
    def view(self):
        poll = self.Poll.get(self.Poll.c.slug=='selfdevpoll')
        if poll:
            objects = self.model.filter(self.model.c.poll==poll.id).order_by(self.model.c.order)
        else:
            objects = []
        _user_view = self._user_info()
        return {'objects':objects, 'poll':poll, 'user_form':_user_view.form, 
            'count':self.Result.count(), 'un_enabled':self.Result.filter(self.Result.c.enabled==False).count()}
    
    def poll(self):
        view = self._user_info()
        return view.run(json_result=True)
    
    @expose('poll_admin')
    @decorators.check_permission('SelfDevPollAdmin')
    def poll_admin(self):
        from uliweb.utils.generic import EditView
        
#        def post_created_form(fcls, model, obj):
#            fcls.managers.html_attrs['url'] = '/config/users/search'
#            fcls.managers.query = obj.managers.all()
        
        fields = ['name', 'desc', 'begin_date', 'end_date', 'link']
        poll = self.Poll.get(self.Poll.c.slug=='selfdevpoll')
        view = EditView(self.Poll, url_for(self.__class__.view), obj=poll,
            fields=fields)
        return view.run()
        
    @expose('modules_admin')
    @decorators.check_permission('SelfDevPollAdmin')
    def modules_admin(self):
        from uliweb.utils.generic import ListView
        
        pageno = int(request.values.get('page', 1)) - 1
        rows_per_page=int(request.values.get('rows', 10))
        
        def action(value, obj):
            return '<a href="%s">%s</a> <a href="%s" onclick="return confirm(\'确定要删除当前模块吗？\');">%s</a>' % (url_for(self.__class__.module_edit, id=obj.id), '编辑', url_for(self.__class__.module_delete, id=obj.id), '删除')
        
        view = ListView(self.model, rows_per_page=rows_per_page, pageno=pageno,
            fields_convert_map={'action':action}, pagination=False)
        return view.run(head=True, body=True)
        
    @decorators.check_permission(perm)
    def module_add(self):
        """
        添加新的板块
        """
        from uliweb.utils.generic import AddView
        
        poll = self.Poll.get(self.Poll.c.slug=='selfdevpoll')
        
        def post_created_form(fcls, obj):
            fcls.kfzx.condition = self.depart_condition
        
        view = AddView(self.model, url_for(self.__class__.modules_admin), 
            default_data={'poll':poll.id}, post_created_form=post_created_form)
        return view.run()
    
    @expose('module_edit/<id>')
    @decorators.check_permission(perm)
    def module_edit(self, id):
        """
        修改板块
        """
        from uliweb.utils.generic import EditView
        
        obj = self.model.get(int(id))
        
        def post_created_form(fcls, data, obj):
            fcls.kfzx.condition = self.depart_condition
        
        view = EditView(self.model, url_for(self.__class__.modules_admin), 
            obj=obj, post_created_form=post_created_form)
        
        return view.run()
    
    def _user_info(self):
        """
        用户信息
        """
        from uliweb.utils.generic import AddView
        from forms import PollForm
        import uuid
        from uliweb.utils import date
        from datetime import timedelta
        
        Selection = self.Selection
        send_mail = self._send_mail
        success_url = url_for(self.__class__.success)
        already_url = url_for(self.__class__.already)
        
        class MyAddView(AddView):
            def on_success(self, d, json_result=False):
                from uliweb.orm import Rollback
                
                selections = d.pop('selections')
                row = self.model.get(self.model.c.email == d['email'])
                d['active_code'] = uuid.uuid1().hex
                d['create_time'] = date.now()
                d['expiry_time'] = date.now() + timedelta(hours=settings.get_var('SELFDEVPOLL/expiry_time'))
                d['ip'] = request.remote_addr
                if row:
                    #如果已经激活，则提示已经投过票了
                    if row.enabled:
                        return json({'success':True, 'data':{'url':already_url}})
                    else:
                        #下面更新原投票结果
                        row.update(**d)
                else:
                    row = self.model(**d)
                    
                #添加头信息
                modules_result = {}
                row.save()
                row.selections.clear()
                p = {}
                for x in selections:
                    module, award = x.split(',')
                    module = int(module)
                    r = modules_result.setdefault(module, [])
                    r.append(award)
                    p[award] = p.setdefault(award, 0) + 1
                    s = Selection(module=module, award=award, 
                        user=row.id, kfzx=d['depart'])
                    s.save()
                
                #check 投票有效性，每个奖项只能是5个
                for (k, v) in settings.get_var('SELFDEVPOLL/awards'):
                    if k not in p or p[k] != 5:
                        Rollback()
                        return json({'success':False, 'message':'每个奖项投票数不能多于或少于5张，请修改！', 'data':{}})

                #send mail
                send_mail(row, modules_result)
                return json({'success':True, 'data':{'url':success_url}})
                    
        def post_created_form(fcls, obj):
            fcls.depart.condition = self.depart_condition
            
        view = MyAddView(self.Result, None, form_cls=PollForm,
            post_created_form=post_created_form)
        return view
    
    def success(self):
        response.template = 'message.html'
        return {'title':'投票成功！', 'message_type':'success', 
            'message':settings.get_var('SELFDEVPOLL/success_message')}
    
    def already(self):
        response.template = 'message.html'
        return {'title':'投票失败！', 'message_type':'warning', 
            'message':settings.get_var('SELFDEVPOLL/already_message')}
    
    def _send_mail(self, row, modules_result):
        from uliweb.utils.common import Serial
        from uliweb.utils import date
        from uliweb.core.html import Tag
        
        now = date.now()

        msg_template = settings.get_var('SELFDEVPOLL/MAIL_MESSAGE')
        url = "%s%s" % (settings.get_var('PARA/DOMAIN'), 
            url_for(self.__class__.poll_selfdev_verify_email, code=row.active_code))
        link = str(Tag('a', url, href=url))
        #处理模块显示的顺序
        orders = self.model.all().order_by(self.model.c.order).values(self.model.c.id, self.model.c.name)
        data = {'year':now.year, 'month':now.month,
            'day':now.day, 'username':row.username,
            'url':link, 'awards':settings.get_var('SELFDEVPOLL/awards'),
            'modules_result':modules_result, 'orders':orders}
        message = application.template('poll_active_mail.html', data)
        to_ = row.email
        mail = {'from_':settings.get_var('PARA/EMAIL_SENDER'), 'to_':to_,
            'subject':settings.get_var('SELFDEVPOLL/MAIL_SUBJECT'), 
            'message':message, 'html':True}
        _type = settings.get_var('SELFDEVPOLL/POLL_SENDMAIL_TYPE', 'print')
        if _type == 'print':
            print mail
        elif _type == 'mail':
            Mail().send_mail(**mail)
        elif _type == 'redis':
            _t = Serial.dump(mail)
            redis = functions.get_redis()
            redis.lpush('send_mails', _t)
    
    @expose('module_delete/<id>')
    @decorators.check_permission(perm)
    def module_delete(self, id):
        """
        删除模块
        """
        from uliweb.utils.generic import DeleteView
        
        obj = self.model.get(int(id))
        
        view = DeleteView(self.model, url_for(self.__class__.modules_admin), 
            url_for(self.__class__.modules_admin),
            obj=obj)
        return view.run()
    
    
    @expose('verify_email')
    def poll_selfdev_verify_email(self):
        from uliweb.orm import get_model, do_
        import datetime
        from datetime import date
        
        SelfdevPoll_user = get_model('selfdevpoll_user')
        #获取地址栏验证码
        code = request.GET.get('code')
        code = str(code)
        selfdevpoll_obj = SelfdevPoll_user.get(SelfdevPoll_user.c.active_code == code)
        title = u'自主研发优秀模块网上投票结果！'
        _type = 'success'
        if selfdevpoll_obj:
            if  not selfdevpoll_obj.enabled and selfdevpoll_obj.expiry_time >= datetime.datetime.now():
                selfdevpoll_obj.enabled = True
                selfdevpoll_obj.active_time = datetime.datetime.now()
                selfdevpoll_obj.save()
                message = u'您的投票激活成功！'
            elif selfdevpoll_obj.enabled:
                message = u'您的投票已激活！'
            elif selfdevpoll_obj.expiry_time < datetime.datetime.now():
                message = u'已超过激活时间，请重新投票！'
                _type = 'warning'
        else:
            message = u'激活码错误，请重新投票！'
            _type = 'warning'
        
        response.template = 'message.html'
        return {'message':message, 'title':title, 'message_type':_type}
    
    def details(self):
        from uliweb.utils.generic import ListView
        
        poll = self.Poll.get_or_notfound(self.Poll.c.slug=='selfdevpoll')
        
        pageno = int(request.values.get('page', 1)) - 1
        rows_per_page=int(request.values.get('rows', 10))
        
        condition = None
        name = request.GET.get('name', '')
        if name:
            condition = self.Result.c.username.like('%'+name+'%') | self.Result.c.email.like('%'+name+'%')

        def enabled(value, obj):
            if value:
                return '<span title="已激活" class="enabled_flag">&radic;</span>'
            else:
                return '<span title="未激活" class="enabled_flag"><font color="red">&times;</font></span>'
            
        fields_convert_map = {'enabled':enabled}
        order_by = (self.Result.c.depart, self.Result.c.username, self.Result.c.email)
        view = ListView(self.Result, condition=condition, pageno=pageno, 
            rows_per_page=rows_per_page,
            order_by=order_by, template_data={'page':pageno+1, 'name':name},
            fields_convert_map=fields_convert_map, table_class_attr='table zebra-striped')
        return view.run(head=True, body=True)
